package com.cloudkinto.cron;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.cloudkinto.common.common.DateUtils;
import com.cloudkinto.common.constant.GlobalConstants;
import com.cloudkinto.common.constant.SysConstant;
import com.cloudkinto.common.utils.MathUtils;
import com.cloudkinto.common.utils.TimeUtils;
import com.cloudkinto.common.utils.ali.AliOss;
import com.cloudkinto.dao.*;
import com.cloudkinto.entity.*;
import com.cloudkinto.service.ecang.ECangService;
import com.cloudkinto.service.finance.CompanyAccountService;
import com.cloudkinto.service.finance.CostRecordService;
import com.cloudkinto.service.finance.RechargeRecordService;
import com.cloudkinto.service.invoice.InvoiceRecordService;
import com.cloudkinto.service.mail.MailService;
import com.cloudkinto.service.order.OrderAmazonService;
import com.cloudkinto.service.order.OrderShopifyService;
import com.cloudkinto.service.orderback.OrderBackService;
import com.cloudkinto.service.orderoutput.OrderOutputService;
import com.cloudkinto.service.product.ProductOutService;
import com.cloudkinto.service.product.ProductStockService;
import com.cloudkinto.service.stock.StockLogService;
import com.cloudkinto.service.stock.StockPickUpService;
import com.cloudkinto.service.storage.StorageShelfService;
import com.cloudkinto.service.user.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zhangyy
 * @date 2020/6/18 16:03
 * @description: 生产环境下的定时任务
 */
@ConditionalOnProperty(prefix = "gbc", name = "scheduling", havingValue = "prod")
@Component
public class CronProdService {


    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private OrderInputDao orderInputDao;
    @Autowired
    private StockRecordDao stockRecordDao;
    @Autowired
    private ProductInfoDao productInfoDao;
    @Autowired
    private StockHistoryDao stockHistoryDao;
    @Autowired
    private StockHistoryDetailDao stockHistoryDetailDao;
    @Autowired
    private CompanyAccountService mCostService;
    @Autowired
    private OrderOutputService mOrderOutService;
    @Autowired
    private ExchangeRateDao mExchangeRateDao;
    @Autowired
    private StorageDao storageDao;
    @Autowired
    private CostRecordService costRecordService;
    @Autowired
    private CompanyDao companyDao;
    @Autowired
    private ShopDao shopDao;
    @Autowired
    private StockLogService stockLogService;
    @Autowired
    private OrderAmazonService mOrderAmzonService;
    @Autowired
    private OrderShopifyService mShopifyOrderService;
    @Autowired
    private InvoiceRecordService invoiceRecordService;
    @Autowired
    private MailService mailService;
    @Autowired
    private ProductStockService productStockService;
    @Autowired
    private OrderBackService orderBackService;
    @Autowired
    private ECangService eCangService;
    @Autowired
    private StorageShelfService storageShelfService;

    @Autowired
    private CompanyStoragePriceDao storagePriceDao;
    @Autowired
    private UserService userService;
    @Autowired
    private ProductOutService productOutService;
    @Autowired
    private RechargeRecordService mRechargeRecordSerivce;
    @Autowired
    private StockPickUpService stockPickUpService;

    /**
     * 定时生成波次
     */
    /**
     * 10分钟
     */
//    @Scheduled(initialDelay = 1000 * 20, fixedRate = 600000)
    @Scheduled(fixedRate = 600000)
    public void timingGeneratePickup() {
        stockPickUpService.generatePickup();
    }


//        /**
//     * 一次性
//     */
//    @Scheduled(fixedRate = Long.MAX_VALUE)
//    public void setOrderTypeSync() {
//        mOrderOutService.setOrderTypeSync();
//        System.out.println("setOrderTypeSync================================");
//    }


//    /**
//     * 一次性
//     */
//    @Scheduled(fixedRate = Integer.MAX_VALUE)
//    public void matchPlatformTime() {
//        productOutService.matchPlatformTime();
//        System.out.println("matchPlatformTime================================");
//    }

    /**
     * 常开 6 小时一次 近一天的订单
     */
    @Scheduled(fixedRate = 1000 * 60 * 60 * 6)
    public void matchPlatformTimeUtils() {
        productOutService.matchPlatformTimeUtils();
    }


    /**
     * 校验异常库位 每天凌晨4点
     */
    @Scheduled(cron = "0 0 4 * * ?")
    public void rackMessageNotice() {
        storageShelfService.rackMessageNotice();
    }


    //每天凌晨12点
    @Scheduled(cron = "1 0 0 * * ?")
    public void testTasks() {
        Date date = new Date();
        boolean isC = false;
        LambdaQueryWrapper<StockRecordDo> wrapper = new LambdaQueryWrapper<>();
        wrapper.and(stockRecordDoLambdaQueryWrapper -> stockRecordDoLambdaQueryWrapper.gt(StockRecordDo::getCanSellCount, 0).or()
                .gt(StockRecordDo::getCanotSellCount, 0));
        List<StockRecordDo> stockRecordDoList = stockRecordDao.selectList(wrapper);
        double jpyRate = getRate(0);
        double usdRate = getRate(1);
        //得到相同的公司list 组成一个map
        Map<Long, List<StockRecordDo>> mapByCompany = stockRecordDoList.stream().filter(stockRecordDo ->
                stockRecordDo.getCanSellCount() > 0 || stockRecordDo.getCanotSellCount() > 0).collect(Collectors.groupingBy(StockRecordDo::getCompanyId));
        if (!CollectionUtils.isEmpty(mapByCompany)) {
            for (Long companyId : mapByCompany.keySet()) {
                CompanyDo companyDo = companyDao.selectById(companyId);
                List<CompanyStoragePriceDo> priceDoList = storagePriceDao.selectList(new LambdaQueryWrapper<CompanyStoragePriceDo>()
                        .eq(CompanyStoragePriceDo::getCompanyId, companyId));
                List<StockRecordDo> recordDoList = mapByCompany.get(companyId);
                //得到此家公司的子店铺list  组成一个map
                Map<Long, List<StockRecordDo>> mapByShop = recordDoList.stream().collect(Collectors.groupingBy(StockRecordDo::getShopId));
                for (Long shopId : mapByShop.keySet()) {
                    List<StockRecordDo> recordDos = mapByShop.get(shopId);
                    List<StockRecordDo> recordDoList1 = mapByCompany.get(companyId);
                    //得到此店铺在此仓库下的list 组成map
                    Map<Long, List<StockRecordDo>> mapStorage = recordDos.stream().collect(Collectors.groupingBy(StockRecordDo::getStorageId));
                    for (Long storageId : mapStorage.keySet()) {
                        double longTimeValue = 0;//长期库存减值
                        int canSell = 0, freezeCount = 0, repairingCount = 0, canNotSell = 0;
                        List<StockRecordDo> storageRecords = mapStorage.get(storageId);
                        if (storageRecords == null) continue;
                        double totalVolume = 0, value = 0, totalCost = 0;
                        double v1Volume = 0, v2Volume = 0, v3Volume = 0, brokenVolume = 0;
                        StorageDo storageDo = storageDao.selectById(storageId);
                        for (StockRecordDo stockRecordDo : storageRecords) {
                            //v1待转运数量不计入仓储费
                            int v1Count = 0, v2Count = 0, v3Count = 0;
                            int stockCount = stockRecordDo.getCanSellCount() + stockRecordDo.getFreezeCount() + stockRecordDo.getRepairingCount();
                            ProductInfoDo productInfoDo = productInfoDao.selectById(stockRecordDo.getProductInfoId());
                            if (productInfoDo == null) continue;
                            //v3 阶梯仓库费
                            //60天内数量
                            int v1days = 60;
                            int v2days = 180;
                            int freedays = 6;
                            if (priceDoList != null && priceDoList.size() > 0) {
                                for (CompanyStoragePriceDo priceDo : priceDoList) {
                                    if (storageId.equals(priceDo.getStorageId()) || (
                                            priceDo.getStorageId() == null &&
                                                    storageDo.getStorageArea().intValue() == priceDo.getStorageType())) {
                                        if (priceDo.getV1Days() != 0)
                                            v1days = priceDo.getV1Days();
                                        if (priceDo.getV2Days() != 0)
                                            v2days = priceDo.getV2Days();
                                        if (priceDo.getFreeDays() != 0)
                                            freedays = priceDo.getFreeDays();
                                        if (priceDo.getV1Price() != 0)
                                            storageDo.setDayPrice(priceDo.getV1Price() * 1.1F);
                                        if (priceDo.getV2Price() != 0)
                                            storageDo.setDayPrice1(priceDo.getV2Price() * 1.1F);
                                        if (priceDo.getV3Price() != 0)
                                            storageDo.setDayPrice2(priceDo.getV3Price() * 1.1F);
                                    }
                                }
                            }
                            int countLT60 = stockLogService.selectInCount(stockRecordDo.getStorageId(), stockRecordDo.getShopId(), stockRecordDo.getProductInfoId(), productInfoDo.getCommoditySku(), v1days);
                            if (stockCount <= countLT60) {
                                v1Count = stockCount;
                                //v2新增7天内都无需费用针对于所有类型适用
                            } else {
                                v1Count = countLT60;
                                //60-180天内数量
                                int countLT180 = stockLogService.selectInCount(stockRecordDo.getStorageId(), stockRecordDo.getShopId(), stockRecordDo.getProductInfoId(), productInfoDo.getCommoditySku(), v2days);
                                if (stockCount <= countLT180) {
                                    v2Count = stockCount - v1Count;
                                } else {
                                    v2Count = countLT180 - v1Count;
                                    //180天以上数量
                                    v3Count = stockCount - countLT180;
                                }
                            }
                            LambdaUpdateWrapper<StockRecordDo> recordDoLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                            recordDoLambdaUpdateWrapper.set(StockRecordDo::getV1Count, v1Count);
                            recordDoLambdaUpdateWrapper.set(StockRecordDo::getV2Count, v2Count);
                            recordDoLambdaUpdateWrapper.set(StockRecordDo::getV3Count, v3Count);
                            recordDoLambdaUpdateWrapper.eq(StockRecordDo::getId, stockRecordDo.getId());
                            stockRecordDao.update(null, recordDoLambdaUpdateWrapper);
                            int freeCount = 0;
                            //C1032 在关东仓库应用独立仓储价格
                            if (companyId.intValue() == 32 && storageDo.getStorageArea().intValue() == 1) {
                                storageDo.setDayPrice(33F);
                                storageDo.setDayPrice1(49.5F);
                                storageDo.setDayPrice2(99F);
                                freeCount = stockRecordDao.getOrderOutPut(-1, stockRecordDo.getProductInfoId(), shopId, storageId, DateUtils.passingDate(new Date(), -freedays));
                            } else if (companyId.intValue() == 300 || companyId.intValue() == 346) {//1300和1346走全量免仓租，数量在company_storage_price配置
                                freeCount = stockRecordDao.getOrderOutPut(-1, stockRecordDo.getProductInfoId(), shopId, storageId, DateUtils.passingDate(new Date(), -freedays));
                            } else if (companyId.intValue() == 26) {
                                //1026仓储费：60-180天仓储费：90降到70 2023/5/6
                                storageDo.setDayPrice1(77F);
                                freeCount = stockRecordDao.getOrderOutPut(1, stockRecordDo.getProductInfoId(), shopId, storageId, DateUtils.passingDate(new Date(), -freedays));
                            } else {
                                freeCount = stockRecordDao.getOrderOutPut(1, stockRecordDo.getProductInfoId(), shopId, storageId, DateUtils.passingDate(new Date(), -freedays));
                            }
                            if (freeCount < 0) {
                                freeCount = 0;
                            }
                            v1Count = v1Count - freeCount < 0 ? 0 : v1Count - freeCount;
                            if (companyId == 1) {
//                                v1Count = stockCount;
                                longTimeValue = longTimeValue + countOldFee(stockRecordDo, productInfoDo, usdRate / jpyRate);
                            }
                            canSell += stockCount > 0 ? stockCount : 0;
                            freezeCount += stockRecordDo.getFreezeCount() > 0 ? stockRecordDo.getFreezeCount() : 0;
                            repairingCount += stockRecordDo.getRepairingCount() > 0 ? stockRecordDo.getRepairingCount() : 0;

                            canNotSell += stockRecordDo.getCanotSellCount() > 0 ? stockRecordDo.getCanotSellCount() : 0;
                            value += ((productInfoDo.getReportPrice() == null ? 0 : productInfoDo.getReportPrice()) * (stockRecordDo.getCanotSellCount() + stockRecordDo.getCanSellCount() +
                                    (stockRecordDo.getFreezeCount() > 0 ? stockRecordDo.getFreezeCount() : 0) + (stockRecordDo.getRepairingCount() > 0 ? stockRecordDo.getRepairingCount() : 0)));
                            float v = productInfoDo.getHeight() * productInfoDo.getWidth() * productInfoDo.getLength();
//                            v1Volume += new BigDecimal(v * (v1Count) / 1000000).doubleValue();
                            v1Volume = MathUtils.add(v1Volume, MathUtils.div(MathUtils.mul(v, v1Count), 1000000));
//                            v2Volume += new BigDecimal(v * (v2Count) / 1000000).doubleValue();
                            v2Volume = MathUtils.add(v2Volume, MathUtils.div(MathUtils.mul(v, v2Count), 1000000));
//                            v3Volume += new BigDecimal(v * (v3Count) / 1000000).doubleValue();
                            v3Volume = MathUtils.add(v3Volume, MathUtils.div(MathUtils.mul(v, v3Count), 1000000));
//                            brokenVolume += new BigDecimal(v * stockRecordDo.getCanotSellCount() / 1000000).doubleValue();
                            brokenVolume = MathUtils.add(brokenVolume, MathUtils.div(MathUtils.mul(v, stockRecordDo.getCanotSellCount()), 1000000));

                            double cost = new BigDecimal(v * v1Count * storageDo.getDayPrice() + v * v2Count * storageDo.getDayPrice1()
                                    + v * v3Count * storageDo.getDayPrice2() + v * stockRecordDo.getCanotSellCount() * storageDo.getDayPrice2()).doubleValue() / 1000000;
                            StockHistoryDetailDo stockHistoryDo = new StockHistoryDetailDo();
                            stockHistoryDo.setStorageId(storageId);
                            stockHistoryDo.setCanSell(stockRecordDo.getCanSellCount() > 0 ? stockRecordDo.getCanSellCount() : 0);
                            stockHistoryDo.setFreezeCount(stockRecordDo.getFreezeCount() > 0 ? stockRecordDo.getFreezeCount() : 0);
                            stockHistoryDo.setRepairingCount(stockRecordDo.getRepairingCount() > 0 ? stockRecordDo.getRepairingCount() : 0);
                            stockHistoryDo.setCanotSell(stockRecordDo.getCanotSellCount() > 0 ? stockRecordDo.getCanotSellCount() : 0);
                            stockHistoryDo.setV1Count(v1Count);
                            stockHistoryDo.setV2Count(v2Count);
                            stockHistoryDo.setV3Count(v3Count);
                            stockHistoryDo.setV4Count(freeCount);
                            stockHistoryDo.setCost(cost);
                            stockHistoryDo.setCreateDate(date);
                            stockHistoryDo.setProductInfoId(stockRecordDo.getProductInfoId());
                            stockHistoryDo.setShopId(shopId);
                            stockHistoryDo.setCompanyId(companyId);
                            stockHistoryDo.setDeleteFlag(SysConstant.DELETE_FLAG_FALSE);
                            stockHistoryDetailDao.insert(stockHistoryDo);
                        }
                        totalVolume = MathUtils.add(totalVolume, v1Volume ,v2Volume, v3Volume , brokenVolume);
//                        totalVolume += (v1Volume + v2Volume + v3Volume + brokenVolume);
                        if (storageDo != null) {
                            //1. 可售库存费算法 = (可售数量-7天免仓租数量)  * 体积
                            if (companyId == 1) {
                                totalCost = new BigDecimal((v1Volume + v2Volume + v3Volume) * storageDo.getDayPrice()).doubleValue();
                                totalCost += new BigDecimal(brokenVolume * storageDo.getDayPrice2()).doubleValue();
                            } else if (companyId.intValue() == 109 || companyId.intValue() == 95) {
                                totalCost = new BigDecimal((v1Volume + v2Volume + v3Volume) * 60).doubleValue();
                                totalCost += new BigDecimal(brokenVolume * 60).doubleValue();
                            } else {
                                totalCost = new BigDecimal(v1Volume * storageDo.getDayPrice() + v2Volume * storageDo.getDayPrice1()
                                        + v3Volume * storageDo.getDayPrice2()).doubleValue();
                                totalCost += new BigDecimal(brokenVolume * storageDo.getDayPrice2()).doubleValue();
                            }
                            // 2. 不良库存算法 = 每件* dayPrice
                        }
                        if (companyId.intValue() == 109 && storageDo.getId() == 11) {
                            totalCost = 1700 / 30 * 100;
                        }
                        totalCost = new BigDecimal(totalCost).setScale(2, RoundingMode.HALF_UP).doubleValue();
                        StockHistoryDo stockHistoryDo = new StockHistoryDo();
                        stockHistoryDo.setCanotSell(canNotSell);
                        stockHistoryDo.setStorageId(storageId);
                        stockHistoryDo.setCanSell(canSell);
                        stockHistoryDo.setFreezeCount(freezeCount);
                        stockHistoryDo.setRepairingCount(repairingCount);
                        stockHistoryDo.setTotalVolume(totalVolume);
                        stockHistoryDo.setV1Volume(v1Volume);
                        stockHistoryDo.setV2Volume(v2Volume);
                        stockHistoryDo.setV3Volume(v3Volume);
                        stockHistoryDo.setCost(totalCost);
                        stockHistoryDo.setValue(value);
                        stockHistoryDo.setLongTimeCost(longTimeValue);
                        stockHistoryDo.setCreateDate(date);
                        stockHistoryDo.setShopId(shopId);
                        stockHistoryDo.setCompanyId(companyId);
                        stockHistoryDo.setDeleteFlag(SysConstant.DELETE_FLAG_FALSE);
                        stockHistoryDao.insert(stockHistoryDo);
                        ShopDo shopDo = shopDao.selectById(shopId);
                        if (shopDo == null || storageDo == null || totalCost < 1) continue;
                        costRecordService.add(2, shopDo.getShopName() + TimeUtils.getCurrentDateFormat("MM-dd")
                                + storageDo.getCode() + "仓储费", totalCost, shopId, companyId, stockHistoryDo.getId());
                        if (longTimeValue > 0) {
                            costRecordService.add(2, shopDo.getShopName() + TimeUtils.getCurrentDateFormat("MM-dd")
                                    + storageDo.getCode() + "长期库存减值", longTimeValue, shopId, companyId, stockHistoryDo.getId());
                        }
                    }
                }
            }
        }

    }

    private double countOldFee(StockRecordDo stockRecordDo, ProductInfoDo productInfoDo, double rate) {
        int v1Count = 0, v2Count = 0, v3Count = 0, v4Count = 0, v5Count = 0, v6Count = 0;
        Calendar calendar = Calendar.getInstance();
        int countLT90 = stockLogService.selectInCount(stockRecordDo.getStorageId(), stockRecordDo.getShopId(), stockRecordDo.getProductInfoId(), productInfoDo.getCommoditySku(), 90);
        if (stockRecordDo.getCanSellCount() <= countLT90) {
            v1Count = stockRecordDo.getCanSellCount();
            //v2新增7天内都无需费用针对于所有类型适用
        } else {
            v1Count = countLT90;
            //90-120天内数量
            int countLT120 = stockLogService.selectInCount(stockRecordDo.getStorageId(), stockRecordDo.getShopId(), stockRecordDo.getProductInfoId(), productInfoDo.getCommoditySku(), 120);
            if (stockRecordDo.getCanSellCount() <= countLT120) {
                v2Count = stockRecordDo.getCanSellCount() - v1Count;
            } else {
                v2Count = countLT120 - countLT90;
                //120-150天内数量
                int countLT150 = stockLogService.selectInCount(stockRecordDo.getStorageId(), stockRecordDo.getShopId(), stockRecordDo.getProductInfoId(), productInfoDo.getCommoditySku(), 150);
                if (stockRecordDo.getCanSellCount() <= countLT150) {
                    v3Count = stockRecordDo.getCanSellCount() - countLT120;
                } else {
                    v3Count = countLT150 - countLT120;
                    //150-180天内数量
                    int countLT180 = stockLogService.selectInCount(stockRecordDo.getStorageId(), stockRecordDo.getShopId(), stockRecordDo.getProductInfoId(), productInfoDo.getCommoditySku(), 180);
                    if (stockRecordDo.getCanSellCount() <= countLT180) {
                        v4Count = stockRecordDo.getCanSellCount() - countLT150;
                    } else {
                        //180-210天内数量
                        int countLT210 = stockLogService.selectInCount(stockRecordDo.getStorageId(), stockRecordDo.getShopId(), stockRecordDo.getProductInfoId(), productInfoDo.getCommoditySku(), 210);
                        if (stockRecordDo.getCanSellCount() <= countLT210) {
                            v5Count = stockRecordDo.getCanSellCount() - countLT180;
                        } else {
                            v5Count = countLT210 - countLT180;
                            //210天以上

                        }
                    }
                }
            }
        }
        if (productInfoDo.getReportPrice() == null)
            productInfoDo.setReportPrice(0F);
        double reportPrice = productInfoDo.getReportPrice() * rate;
        //长期堆放仓库，进行货物贬值处理④；超过90天的库存减值10%(每天扣减千分之3.3)；超过120天，减值30%；超过150天减值60%；超过180天，减值为0(平台堆放天数记录为准）
        return new BigDecimal((v2Count * 0.00333 * +
                v3Count * 0.01 + v4Count * 0.02 +
                v5Count * 0.01) * reportPrice).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    @Scheduled(cron = "0 13 7-21 * * ?")
    public void getExpressStatustransit() {
        mOrderOutService.getExpressStatus("transit");
    }

    @Scheduled(cron = "0 25 7-21 * * ?")
    public void getExpressStatusPickup() {
        mOrderOutService.getExpressStatus("delivered");
    }

    @Scheduled(cron = "0 36 7-21 * * ?")
    public void getExpressStatusdelivered() {
        mOrderOutService.getExpressStatus("pickup");
    }

    @Scheduled(cron = "0 42 7-21 * * ?")
    public void getExpressStatusundelivered() {
        mOrderOutService.getExpressStatus("undelivered");
    }

    @Scheduled(cron = "0 53 7-21 * * ?")
    public void getExpressStatusexception() {
        mOrderOutService.getExpressStatus("exception");
    }

    @Scheduled(cron = "0 17 11,16,22 * * ?")
    public void postExpressCode() {
        mOrderOutService.postExpress2Api();
    }

    @Scheduled(cron = "0 09 17 * * ?")
    public void updateArchivedExpressCode() {
        mOrderOutService.updateArchivedExpressCode();
    }

    @Scheduled(cron = "0 0 23 * * ?")
    public void updateAmount() {
        mCostService.updateAmount();
    }

    @Scheduled(initialDelay = 1000 * 60 * 2, fixedRate = 1000 * 60 * 20)
    public void autoSyncShippingOrder() {
        eCangService.autoSyncShippingOrder();

    }

    @Scheduled(cron = "0 5 16 * * *")
//    @Scheduled(initialDelay = 1000 * 60 * 2, fixedRate = 1000 * 60 * 120)
    public void sendMail2SKL() {
//        if (TimeUtils.getWeekOfDate(new Date()) < 6)
        mOrderOutService.sendYamatoSizeMail();
    }

//    @Scheduled(fixedDelay = 1000 * 10)
//    public void sendMail2SKL1() {
////        if (TimeUtils.getWeekOfDate(new Date()) < 6)
//        mOrderOutService.sendYamatoSizeMail();
//    }

    /**
     * 定时废弃退货
     */
    @Scheduled(cron = "0 0 03 * * ?")
    public void autoDropOverTime() {
        orderBackService.autoDropOverTime();
        orderBackService.autoDropOverTime2();
//        orderBackService.autoCompletedOrder();
    }

    @Scheduled(cron = "0 0 22 * * ?")
    public void fianceChinaBank() {
        //https://www.nowapi.com/
//        String url = "http://api.k780.com/?app=finance.rate_cnyquot&curno=JPY&&appkey=45417&sign=fa1e01ee26c61537f590e6a543303b18&format=json";
//        String body = OkHttpUtils.okHttpRequest(url, HttpMethod.POST.name(), "");
//        FianceChinaBankVo fianceChinaBank = JSONObject.parseObject(body, FianceChinaBankVo.class);
//        System.out.println(fianceChinaBank.getResult().getJPY().getBOC().getMiddle());
//        ExchangeRateDo exchangeRateDo = new ExchangeRateDo("BOC", "0",
//                Float.parseFloat(fianceChinaBank.getResult().getJPY().getBOC().getMiddle()) + 0.2F, fianceChinaBank.getResult().getJPY().getBOC().getUpddate());
//        mExchangeRateDao.insert(exchangeRateDo);
//
//        String url1 = "http://api.k780.com/?app=finance.rate_cnyquot&curno=USD&&appkey=45417&sign=fa1e01ee26c61537f590e6a543303b18&format=json";
//        String body1 = OkHttpUtils.okHttpRequest(url1, HttpMethod.POST.name(), "");
//        FianceChinaBankVo fianceChinaBank1 = JSONObject.parseObject(body1, FianceChinaBankVo.class);
//        ExchangeRateDo exchangeRateDo1 = new ExchangeRateDo("BOC", "1",
//                Float.parseFloat(fianceChinaBank1.getResult().getUSD().getBOC().getCn_sell()), fianceChinaBank1.getResult().getUSD().getBOC().getUpddate());
//        mExchangeRateDao.insert(exchangeRateDo1);

    }


    @Scheduled(fixedDelay = 10 * 60 * 1000)
    public void dataStatisticsSet() {
        Integer fbaInputCount = (Integer) redisTemplate.opsForValue().get(GlobalConstants.FBA_INPUT_KEY);
        Integer jpSendOutCount = (Integer) redisTemplate.opsForValue().get(GlobalConstants.JP_SEND_OUT_KEY);
        Integer orderBackOutCount = (Integer) redisTemplate.opsForValue().get(GlobalConstants.ORDER_BACK_KEY);
        Integer storageAreaCount = (Integer) redisTemplate.opsForValue().get(GlobalConstants.STORAGE_AREA_KEY);
        if (fbaInputCount == null) {
            fbaInputCount = 62901229;
        } else {
            int random = new Random().nextInt(3000) + 1000;
            fbaInputCount += random;
        }

        if (jpSendOutCount == null) {
            jpSendOutCount = 5161956;
        } else {
            int random = new Random().nextInt(100) + 1000;
            jpSendOutCount += random;
        }

        if (orderBackOutCount == null) {
            orderBackOutCount = 778307;
        } else {
            int random = new Random().nextInt(3000) + 100;
            orderBackOutCount += random;
        }

        if (storageAreaCount == null) {
            storageAreaCount = 79200;
        }

        redisTemplate.opsForValue().set(GlobalConstants.FBA_INPUT_KEY, fbaInputCount);
        redisTemplate.opsForValue().set(GlobalConstants.JP_SEND_OUT_KEY, jpSendOutCount);
        redisTemplate.opsForValue().set(GlobalConstants.ORDER_BACK_KEY, orderBackOutCount);
        redisTemplate.opsForValue().set(GlobalConstants.STORAGE_AREA_KEY, storageAreaCount);

    }

    @Scheduled(cron = "0 0/20 * * * ?")
    @Async
    public void refreshAmazonOrder() {
        mOrderAmzonService.autoRefreshOrder();
    }

    @Scheduled(cron = "0 10/20 7-22 * * ?")
    @Async
    public void refreshShopifyOrder() {
        mShopifyOrderService.autoRefreshOrder();
    }


    private double getRate(int type) {
        //实时汇率
        QueryWrapper<ExchangeRateDo> wrapper = new QueryWrapper();
        wrapper.orderByDesc("id");
        wrapper.eq("type", type);
        wrapper.last("limit 1");
        ExchangeRateDo exchangeRateDo = mExchangeRateDao.selectOne(wrapper);
        return exchangeRateDo.getRate();
    }

    @Scheduled(cron = "0 01 0 8 * ?")
    public void timingReview() {
        invoiceRecordService.timingReview();
    }

    /**
     * 定时同步邮箱 最新邮件
     */
    /**
     * 10分钟
     */
    @Scheduled(initialDelay = 1000 * 20, fixedRate = 600000)
//    @Scheduled(fixedRate = 600000)
    public void timingSyncNewMail() {
        mailService.timingSynchronizationMail("new");
        mRechargeRecordSerivce.matchSmsList();
    }


    /**
     * 同步初始库存
     */
//    @Scheduled(fixedDelay = Long.MAX_VALUE)
//    public void syncStock(){
//        productStockService.syncStock();
//    }

    /**
     * 定时匹配 发票链接
     */
    @Scheduled(initialDelay = 1000 * 20, fixedRate = 600000 * 2)
    public void timingMatchInvoiceLink() {
        invoiceRecordService.timingMatchInvoiceLink();

    }


    /**
     * 每天定时删除 阿里云 oss 临时文件夹图片
     */
    @Scheduled(cron = "0 0 3 * * *")
    public void timingAutoDeleteFile() {
        AliOss.autoDeleteFile();
    }


    /**
     * 每月月初一号 更新redis 上月库存出库信息
     */
    @Scheduled(cron = "0 0 0 1 * *")
    public void timingRefreshOutVolResListRedis() {
        storageShelfService.refreshOutVolResListRedis();
    }


//    /**
//     * 给所有公司 生成默认角色
//     */
//    @Scheduled(fixedRate = Long.MAX_VALUE)
//    public void createRoleForCompany() {
//        System.out.println("开始生成新角色");
//        userService.createRoleForCompany();
//        System.out.println("结束生成新角色");
//    }

}